package com.core.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;

import com.core.dao.GenericDao;
import com.core.hibernate.MyHibernateDaoSupport;

public class GenericDaoImpl<E, PK extends Serializable> extends
		MyHibernateDaoSupport implements GenericDao<E, PK> {

	protected DetachedCriteria createDetachedCriteria() {
		return DetachedCriteria.forClass(getEntityClass());
	}

	@Override
	public void delete(E persistentObject) throws DataAccessException {
		getHibernateTemplate().delete(persistentObject);
	}

	@Override
	public E find(PK id) throws DataAccessException {
		return (E) getHibernateTemplate().get(getEntityClass(), id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> findAll() throws DataAccessException {
		return getHibernateTemplate().findByCriteria(createDetachedCriteria());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> findAllByProperty(String propertyName, Object value)
			throws DataAccessException {
		DetachedCriteria criteria = createDetachedCriteria();
		criteria.add(Restrictions.eq(propertyName, value));
		return getHibernateTemplate().findByCriteria(criteria);
	}

	@SuppressWarnings("unchecked")
	public List<E> findByExample(E object) throws DataAccessException {
		return getHibernateTemplate().findByExample(object, 0, 1);
	}

	protected Class<E> getEntityClass(){
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public PK save(E entity) throws DataAccessException {
		return (PK) getHibernateTemplate().save(entity);
	}

	@Override
	public void saveOrUpdate(E transientObject) throws DataAccessException {
		getHibernateTemplate().saveOrUpdate(transientObject);
	}

	@Override
	public void update(E transientObject) throws DataAccessException {
		getHibernateTemplate().update(transientObject);
	}

}
